package com.fingerth.demo.ui

import android.view.View
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.fingerth.demo.R
import com.fingerth.demo.base.BaseAct
import com.fingerth.demo.bean.Picture1
import com.fingerth.demo.bean.base.BaseResListBean
import com.fingerth.demo.databinding.ActivityUse1Binding
import com.fingerth.demo.net.retrofit.NetworkUtils
import com.fingerth.demo.net.retrofit.coroutine.requestData
import com.fingerth.demo.utils.*
import com.fingerth.xadapter.Xadapter

class Use1Activity : BaseAct<ActivityUse1Binding>(), View.OnClickListener {

   private val picWith: Int by lazy { S.getSysWidth(this) / 2 - dp2px(this, 18f) }
   private var mData: BaseResListBean<Picture1>? = null
   private var adapter: Xadapter.XRecyclerAdapter<Picture1>? = null
    override fun initView() {
        setClick(vBinding.barLayout.backIv)
        vBinding.barLayout.titleTv.text = "简单使用"
        onGetPictures()
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.back_iv -> finish()
        }
    }


    private fun initAdapter() {
        mData?.data?.list?.let { pList ->
            if (adapter != null) {
                adapter!!.notify(pList)
            } else {
                adapter = Xadapter<Picture1>(this)
                        .data(pList)
                        .layoutId(R.layout.rv_item_gallery_pic)
                        .bind { c, h, _, p, _ ->
                            h.setText(R.id.num, p.imgs.size.toString())
                            val iv = h.getView<ImageView>(R.id.iv)
                            iv.layoutParams = iv.layoutParams.apply { height = (picWith * p.ratio).toInt() }
                            Glide.with(c).load(p.imgs[0]).apply(RequestOptions.centerCropTransform().place()).into(iv)
                        }
                        .itemClickListener { c, _, _, p, _ -> ToastUtils.showToast(c, p.title) }
                        .create()
                vBinding.rv.adapter = adapter
            }
        }

    }

    private fun onGetPictures() {
        requestData<BaseResListBean<Picture1>?> {
            api = NetworkUtils.httpService.getGallery()
            onFailed { _, _ -> ToastUtils.showNetError(this@Use1Activity) }
            onSuccess {
                mData = it
                initAdapter()
            }
        }
    }

}